<script setup>
import { registerApi } from '@/api/login'
import {
  getStudentListApi,
  getStudentListQueryApi,
  importStudentsExcelApi,
  resetPasswordApi,
  updateUserStatusApi
} from '@/api/user'
import Form from '@/components/User/Form.vue'
import FormAdd from '@/components/common/formAdd.vue'
import Pagization from '@/components/common/pagization.vue'
import Table from '@/components/common/table.vue'
import { useUserStore } from '@/stores/user'
import { dayFormat } from '@/utils/common/dayjs'
import { showStatusMessage } from '@/utils/common/showMessage'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { utils, writeFileXLSX } from 'xlsx'
// 获取年份
const yearData = new Date().getFullYear()
const router = useRouter()

// 表单数据
const formData = ref({
  name: '',
  account: '',
  status: '',
  phone: '',
  grade: '',
  class: '',
  college: '',
  major: '',
  phone: '',
  internship: ''
})
const formModel = [
  {
    prop: 'name',
    label: '姓名',
    type: 'input'
  },
  {
    prop: 'account',
    label: '账号',
    type: 'input'
  },
  {
    prop: 'status',
    label: '状态',
    type: 'select',
    options: [
      { label: '启用', value: '0' },
      { label: '禁用', value: '1' }
    ]
  },
  {
    prop: 'phone',
    label: '手机号码',
    type: 'input'
  },
  {
    prop: 'college',
    label: '学院',
    type: 'selectCollege',
    options: [
      { label: '信息工程学院', value: '信息工程学院' },
      { label: '教育学院', value: '教育学院' },
      { label: '体育学院', value: '体育学院' },
      { label: '健康学院', value: '健康学院' },
      { label: '传媒学院', value: '传媒学院' },
      { label: '工学院', value: '工学院' },
      { label: '商学院', value: '商学院' }
    ]
  },
 
  {
    prop: 'major',
    label: '专业',
    type: 'selectMajor'
  },
  {
    prop: 'class',
    label: '班级',
    type: 'selectClass'
  },
  {
    label: '是否已实习',
    type: 'select',
    prop: 'internship',
    options: [
      { value: 0, label: '未实习' },
      { value: 1, label: '已实习' }
    ]
  }
]
const btnOpt = [
  {
    name: '查询',
    btnType: '',
    prop: 'query'
  },
  {
    name: '新增',
    btnType: 'success',
    prop: 'add'
  },
  {
    name: '重置',
    btnType: 'info',
    prop: 'reset'
  },
  {
    name: '导出',
    btnType: 'warning',
    prop: 'output'
  },
  {
    name: '导入',
    btnType: 'info',
    prop: 'import'
  }
]

// 对话框的显示隐藏
const dialogFormVisible = ref(false)
// ******************注册添加************************
const form = ref({
  identity: '学生',
  studentNumber: '',
  name: '',
  gender: '',
  account: '',
  password: '',
  repassword: '',
  grade: '',
  class: '',
  college: '',
  major: '',
  phone: ''
})

const studentFormOpt = [
  { label: '身份', type: 'input', prop: 'identity' },
  { label: '账号', type: 'input', prop: 'account' },
  { label: '密码', type: 'password', prop: 'password' },
  { label: '确认密码', type: 'password', prop: 'repassword' },
  { label: '学号', type: 'input', prop: 'studentNumber' },
  { label: '姓名', type: 'input', prop: 'name' },
  {
    label: '性别',
    type: 'select',
    prop: 'gender',
    options: [
      { value: '男', label: '男' },
      { value: '女', label: '女' }
    ]
  },
  {
    label: '联系电话',
    type: 'input',
    prop: 'phone'
  },
  {
    label: '学院',
    type: 'selectCollege',
    prop: 'college'
  },
  { label: '专业', type: 'selectMajor', prop: 'major' },
  { label: '班级', type: 'selectClass', prop: 'class' }
]
const btnOptStudent = [
  {
    name: '取消',
    btnType: '',
    prop: 'cancel'
  },
  {
    name: '确定',
    btnType: 'success',
    prop: 'confirm'
  }
]
const formRef = ref(null)
const pagizationToatl = ref(null)
const userStore = useUserStore()
/**
 * 获取表格数据
 */
async function getTableData(data) {
  let res = null

  if (userStore.userInfo.college == '*') {
    res = await getStudentListQueryApi(data)

  } else {
  console.log(userStore.userInfo.college)
    res = await getStudentListQueryApi({
      ...data,
      college: userStore.userInfo.college
    })

  }

  tableData.value = res.data
  pagizationToatl.value = res.total
}
getTableData()
const pagizationRef = ref(null)
const selectFormRef = ref(null)
/**
 * 点击重置按钮
 */
function reset() {
  getTableData()
  pagizationRef.value.reset()
  selectFormRef.value.reset()
}
/**
 * 表单按钮添加事件
 */
function addForm() {
  dialogFormVisible.value = true
}
/**
 * 对话框取消事件
 */
function cancel() {
  formRef.value.reset()
  dialogFormVisible.value = false
}
/**
 * 对话框确定事件
 */
async function confirm(data) {
  const res = await registerApi(data)
  showStatusMessage(res)
  // 对表单的值进行重置
  getTableData()
  // 关闭对话框
  dialogFormVisible.value = false
}
/**
 * 表单查询事件
 * @param {Object} data 查询条件
 */
const queryData = ref(null)
async function query(data) {
  queryData.value = data
  const res = await getStudentListQueryApi(data)
  console.log(res)
  showStatusMessage(res)
  tableData.value = res.data
  pagizationToatl.value = res.total
}
// 导出excel
async function exportToExcel() {
  const dataS = selectFormRef.value.getValue()
  // 获取要导出的业务数据
  const res = await getStudentListQueryApi({ ...dataS, export: true })
  const data = res.data
  // 表头英文字段key
  const tableHeaderKeys = [
    'name',
    'phone',
    'account',
    'class',
    'college',
    'grade',
    'major',
    'studentNumber',
    'internship'
  ]
  // 表头中文字段value
  const tableHeaderValues = ['账号', '联系电话', '班级', '学院', '专业', '学号', '是否实习']
  // 以excel表格的顺序调整后端数据
  const sheetData = data.map((item, index) => {
    let obj = {}
    obj = {
      name: item.name,
      phone: item.phone,
      account: item.account,
      class: item.class,
      college: item.college,
      grade: item.grade,
      major: item.major,
      studentNumber: item.studentNumber,
      internship: item.internship == 0 ? '未实习' : item.internship == 1 ? '正在实习' : '已实习'
    }
    return obj
  })
  // 创建一个工作表
  const worksheet = utils.json_to_sheet(sheetData)
  // 创建一个新的工作簿
  const workbook = utils.book_new()
  // 把工作表添加到工作簿
  utils.book_append_sheet(workbook, worksheet, 'Data')
  // 改写表头
  utils.sheet_add_aoa(worksheet, [tableHeaderValues], { origin: 'A1' })
  writeFileXLSX(workbook, '导出数据.xlsx')
}

/**
 * 表单按钮点击事件
 * @param type 操作类型
 * @param data 表单数据
 */
function handleForm(type, data) {
  // console.log(type, data)
  switch (type) {
    case 'query':
      query(data)
      break
    case 'add':
      addForm()
      break
    case 'output':
      exportToExcel()
      break
    case 'cancel':
      cancel()
      break
    case 'confirm':
      confirm(data)
      break
    case 'reset':
      reset(data)
      break
    case 'import':
      handleUpload(data)
    default:
      break
  }
}
// 列表数据
const tableData = ref([])
const columns = [
  {
    prop: 'account',
    label: '账号'
  },
  {
    prop: 'name',
    label: '姓名'
  },
  {
    prop: 'internship',
    label: '实习情况'
  },
  {
    prop: 'status',
    label: '是否禁用'
  },
  {
    prop: 'college',
    label: '学院'
  },
  {
    prop: 'major',
    label: '专业'
  },
  {
    prop: 'class',
    label: '班级'
  },

  {
    prop: 'identity',
    label: '身份'
  },
  {
    prop: 'gender',
    label: '性别'
  },
  {
    prop: 'phone',
    label: '联系电话'
  }
]
const options = [
  {
    label: '重置密码',
    type: 'primary',
    prop: 'edit'
  }
]

/**
 * 修改账号是否被禁用事件
 * @param data 0|1禁用状态
 */
async function handletTableSwitch(data) {
  console.log(data)
  const res = await updateUserStatusApi({ account: data.account, status: data.status })
  showStatusMessage(res)
}
// 重置密码
const resetPasswordVisible = ref(false)
const resetPasswordForm = ref({
  newPassword: '',
  account: ''
})

function handletTableEdit(data) {
  resetPasswordVisible.value = true
  resetPasswordForm.value.account = data.account
}

// 确认重置密码
async function confirmResetPassword() {
  const res = await resetPasswordApi({
    account: resetPasswordForm.value.account,
    newPassword: resetPasswordForm.value.newPassword
  })
  showStatusMessage(res)
  resetPasswordVisible.value = false
  resetPasswordForm.value = {
    newPassword: '',
    account: ''
  }
}

// 取消重置密码
function cancelResetPassword() {
  resetPasswordVisible.value = false
  resetPasswordForm.value = {
    newPassword: '',
    account: ''
  }
}

/**
 * 表格的操作事件
 * @param {Object} data  操作行的数据
 * @param {String} type 操作类型-'edit'-'delete'
 */
function handleTable(data, type) {
  switch (type) {
    // 修改账号是否被禁用
    case 'switch':
      handletTableSwitch(data)
      break
    case 'edit':
      handletTableEdit(data)
      break

    default:
      break
  }
}
const currentPage=ref(1)
// 分页器条数发生变化
function handleSizeChange(val) {
  const data = selectFormRef.value.getValue()
  console.log('条数发生变化')
  getTableData({ size: val, ...data })
  pagizationRef.value.reset()
}
// 分页器页数发生变化
function handleCurrentChange(page, size) {
  const data = selectFormRef.value.getValue()
  console.log(page, size)
  currentPage.value = page
  getTableData({ page, size, ...data })
}
/**
 * 处理文件上传功能
 * 该函数通过FileReader读取用户上传的文件，并将其转换为JSON格式的数据，以便进一步处理
 * @param {Event} e 文件上传事件，包含上传的文件信息
 */
async function handleUpload(e) {
  const res = await importStudentsExcelApi({ jsonData: e, create_time: dayFormat(new Date()) })
  showStatusMessage(res)
  getTableData()
}
</script>

<template>
  <div class="user-wrapper">
    <div class="user-content">
      <Form
        :data="formData"
        :formOpt="formModel"
        :btnOpt="btnOpt"
        @handleForm="handleForm"
        ref="selectFormRef"
      ></Form>
      <!-- 表格 -->
      <Table
        :tableData="tableData"
        :columns="columns"
        :options="options"
        @handleTable="handleTable"
      >
        <template #firstColumn>
          <el-table-column type="index" label="用户编号" width="100" align="center" />
        </template>
      </Table>
      <!-- 分页 -->
      <Pagization
        v-model="currentPage"
        ref="pagizationRef"
        :total="pagizationToatl"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      ></Pagization>
    </div>
    <!-- 新增用户对话框 -->
    <el-dialog
      v-model="dialogFormVisible"
      title="新增学生用户"
      width="500"
      :close-on-click-modal="false"
      align-center
      destroy-on-close
    >
      <FormAdd
        ref="formRef"
        :data="form"
        :formOpt="studentFormOpt"
        :btnOpt="btnOptStudent"
        @handleForm="handleForm"
      ></FormAdd>
    </el-dialog>
    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="resetPasswordVisible"
      title="重置密码"
      width="400"
      :close-on-click-modal="false"
      align-center
      destroy-on-close
    >
      <el-form :model="resetPasswordForm">
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="resetPasswordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelResetPassword">取消</el-button>
          <el-button type="primary" @click="confirmResetPassword">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.user-wrapper {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: start;
  .user-content {
    width: 100%;
    padding: 30px 50px;
    text-align: left;
    overflow: auto;
  }
}
</style>
